/*
 * StaticArray.hpp
 *
 *  Created on: Sep 21, 2011
 *      Author: dabr
 */

#ifndef STATICARRAY_HPP_
#define STATICARRAY_HPP_

namespace cpac
{

	// Recursive template to build static arrays for us.
	//--------------------------------------
	// _Range  is the total number of elements
	// _Offset is the value of the first element
	// _Type   is the data type of the array.
	//
	// Usage is cpac::static_array< 80, -30 > array; for an 80 element array
	// of ints beginning at -30
	template< int _Range, int _Offset = 0, typename _Type = int >
	struct static_array
	{
		// This will cause the compiler to recurse until it reaches the specialization
		// for our limit
		static_array< _Range - 1, _Offset, _Type > rest;

		// The actual data
		const _Type value;

		// Overloaded subscript operator to make the end-user code more readable
		const _Type operator[](const int index) const
		{
			return reinterpret_cast< _Type const* >(this)[index];
		}

		static_array() : value((_Type)_Range + (_Type)_Offset) {}
	};

	// Specialization of our array that halts the recursion.
	template< int _Offset, typename _Type >
	struct static_array< 0, _Offset, _Type >
	{
		const _Type value;

		const _Type operator[](const int index) const
		{
			return reinterpret_cast< _Type const* >(this)[index];
		}

		static_array() : value( (_Type)0 + (_Type)_Offset) {}
	};
	//--------------------------------------

	// Recursive template to build static arrays for us.
	//--------------------------------------
	// _NumBits is the number of bits to represent (Must be multiple of 8)
	//
	// Usage is cpac::static_array< 8 > char_bit_field; for an 8 element array
	template< int _NumBits >
	struct bit_field
	{
		// This will cause the compiler to recurse until it reaches the specialization
		// for our limit
		bit_field< _NumBits - 1 > rest;

		// The actual data
		bool value : 1;

		// Overloaded subscript operator to make the end-user code more readable
		bool operator[](const int index)
		{
			return reinterpret_cast< bool* >(this)[index];
		}
	};

	// Specialization of our array that halts the recursion.
	template< >
	struct bit_field< 0 >
	{
		bool value : 1;

		bool operator[](const int index)
		{
			return reinterpret_cast< bool* >(this)[index];
		}
	};
	//--------------------------------------

}

#endif /* STATICARRAY_HPP_ */
